﻿using System;
using System.Collections.Generic;

namespace Loki.Engine
{
    public class LokiLinkCollection<TEntityClass, TEntityKey> : LokiCollection<TEntityKey>, IList<TEntityClass>
        where TEntityClass : IAtomicEntity<TEntityKey>
    {
        private Func<TEntityKey, TEntityClass> _Resolver;

        public LokiLinkCollection(Func<TEntityKey, TEntityClass> P_Resolver)
        {
            _Resolver = P_Resolver;
        }

        public LokiLinkCollection(IIndexedEnumerable<TEntityClass, TEntityKey> P_DistantStore)
        {
            _Resolver = x => P_DistantStore[x];
        }

        #region IList<TEntityClass> Members

        public int IndexOf(TEntityClass item)
        {
            return base.IndexOf(item.ID);
        }

        public void Insert(int index, TEntityClass item)
        {
            base.Insert(index, item.ID);
        }

        public new TEntityClass this[int index]
        {
            get
            {
                return _Resolver(base[index]);
            }
            set
            {
                base[index] = value.ID;
            }
        }

        #endregion

        #region ICollection<TEntityClass> Members

        public void Add(TEntityClass item)
        {
            base.Add(item.ID);
        }

        public bool Contains(TEntityClass item)
        {
            return base.Contains(item.ID);
        }

        public void CopyTo(TEntityClass[] array, int arrayIndex)
        {
            TEntityKey[] L_array = new TEntityKey[array.Length];
            base.CopyTo(L_array, arrayIndex);
            for (int i = arrayIndex; i < array.Length; i++)
            {
                array[i] = _Resolver(L_array[arrayIndex]);
            }
        }

        bool ICollection<TEntityClass>.IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(TEntityClass item)
        {
            return base.Remove(item.ID);
        }

        #endregion

        #region IEnumerable<TEntityClass> Members

        public new IEnumerator<TEntityClass> GetEnumerator()
        {
            foreach (var item in base.Items)
            {
                yield return _Resolver(item);
            }
        }

        #endregion
    }
}
